<?php


namespace app\mobile\controller;
use app\model\Address as SelfModel;
use \app\model\CnProv;
use \app\model\CnCity;
use \app\model\CnArea;
use think\facade\View;
class Address extends Base
{


    public function index()
    {
        $data = SelfModel::where('member_id',$this->member_id)->select();
        if($this->request->isPost()){
            return json(['code'=>200,'message'=>'列表','data' => $data]);
        }
        return view('', ['data' => $data]);
    }

    /**
     * 添加
     * @return mixed
     */
    public function create()
    {

        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['member_id'] = $this->member_id;
            $ret = (new SelfModel())->save($param);
            if ($ret) {
                return json(['code' => 200, 'message' => '添加成功']);
            }
            return json(['code' => 400, 'message' => '失败']);
        }
        $prov = CnProv::select();
        return View::fetch('', ['info' => [],'prov'=>$prov,'city'=>[],'area'=>[]]);
    }

    /**
     * 修改
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        $param = $this->request->param();
        $info = SelfModel::find($id);

        if ($this->request->isPost()) {
            $ret = $info->save($param);
            if ($ret !== false) {
                return json(['code' => 200, 'message' => '修改成功']);
            }
            return json(['code' => 400, 'message' => '失败']);
        }
        $prov = CnProv::select();
        $city = CnCity::where('pcode',$info['prov'])->select();
        $area = CnArea::where('pcode',$info['city'])->select();
        return View::fetch('create', ['info' => $info,'prov'=>$prov,'city'=>$city,'area'=>$area]);
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DbException
     * 当前会员的非会员ID
     */
    public function set_default()
    {

        SelfModel::where('id','<>', $this->param['id'])->where('member_id',$this->member_id)->update(['status' => 1]);
        $ret = SelfModel::where('id', $this->param['id'])->update(['status' => 2]);
        if ($ret !== false) {
            return json(['code' => 200, 'message' => '默认地址设置成功']);
        }
        return json(['code' => 400, 'message' => '失败']);
    }
}